﻿using System;
using DynamicGeometry;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using Microsoft.Scripting.Silverlight;

namespace SilverlightDG
{
    public class DLR : ExpressionCompiler
    {
        ScriptRuntime runtime;
        ScriptEngine engine;
        ScriptScope scope;

        public DLR()
        {
            var setup = new ScriptRuntimeSetup();
            setup.HostType = typeof(BrowserScriptHost);
            setup.LanguageSetups.Add(Python.CreateLanguageSetup(null));

            runtime = new ScriptRuntime(setup);
            engine = runtime.GetEngine("Python");
            scope = engine.CreateScope();
        }

        public override Func<double, double> Compile(string expression)
        {
            try
            {
                var source = engine.CreateScriptSourceFromString(
                        string.Format(@"
from math import *

def y(x):
    return {0}

func = y
", expression),
                        Microsoft.Scripting.SourceCodeKind.File);

                CompiledCode code = source.Compile();
                code.Execute(scope);
                var func = scope.GetVariable<Func<double, double>>("func");
                return func;
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}
